using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Collections.Generic;
using Sce.PlayStation.Core;
using Sce.PlayStation.Core.Imaging;
using Sce.PlayStation.Core.Environment;
using Sce.PlayStation.HighLevel.UI;
using VitaReader;

namespace VitaReaderLibPS
{
	
	//book marks management
	//add,delet,jump
    internal class BookMark : ReaderUI
    {
		Label		UILbBookMarkTitle;
		Label		UILbBookMarkListCounter;
		ImageBox	UIImgBookMarkListBk;
		Button		UIBnBookMarkCurrent;
		Button		UIBnBookMarkDelete;
		ScrollPanel	UISpBookMarkListParent;
			Label		UILbBookMarkInfo;
			ListPanel	UILpBookMarks;
		
		private int mCurrentBookMarkItem;
		private List<Button> mBookMarkButton;
		private int mBookMarkCount = 0;
		
		#region readerUI overrides
		public override void Initialize(ReaderScene scene)
		{
			base.Initialize(scene);
			
			#region create
			mRoot = new Panel();
			mRoot.Name = "BookMarkRoot";
			mRoot.BackgroundColor = mScene.ListBackgroundColor;
			//mRoot.BackgroundStyle = DialogBackgroundStyle.Custom;
			//mRoot.CustomBackgroundColor = mScene.ListBackgroundColor;
			{
				UILbBookMarkTitle = new Label();
				UILbBookMarkTitle.Name = "UILbBookMarkTitle";
				UILbBookMarkTitle.Font = mScene.TitleFont;
				UILbBookMarkTitle.TextColor = mScene.TitleColor;
				UILbBookMarkTitle.HorizontalAlignment = HorizontalAlignment.Left;
				this.mRoot.AddChildLast(UILbBookMarkTitle);
				
				UILbBookMarkListCounter = new Label();
				UILbBookMarkListCounter.Name = "UILbBookMarkListCounter";
				UILbBookMarkListCounter.Font = mScene.FontSet.Small;
				UILbBookMarkListCounter.TextColor = mScene.TitleColor;
				UILbBookMarkListCounter.HorizontalAlignment = HorizontalAlignment.Right;
				this.mRoot.AddChildLast(UILbBookMarkListCounter);
				
				UIImgBookMarkListBk = new ImageBox();
				UIImgBookMarkListBk.Name = "UIImgBookMarkListBk";
	            UIImgBookMarkListBk.Image = mScene.ListBackgroundImage;
				UIImgBookMarkListBk.ImageScaleType = ImageScaleType.Stretch;
				UIImgBookMarkListBk.Visible = true;
				this.mRoot.AddChildFirst(UIImgBookMarkListBk);
				
				UIBnBookMarkCurrent = new Button();
	            UIBnBookMarkCurrent.Name = "UIBnBookMarkCurrent";
	            UIBnBookMarkCurrent.TextColor = mScene.ButtonTextColor;
	            UIBnBookMarkCurrent.TextFont = mScene.ButtonTextFont;
	            UIBnBookMarkCurrent.Style = ButtonStyle.Custom;
	            UIBnBookMarkCurrent.CustomImage = mScene.ButtonImage;
				UIBnBookMarkCurrent.Visible = true;
				this.mRoot.AddChildLast(UIBnBookMarkCurrent);
				
				UIBnBookMarkDelete = new Button();
	            UIBnBookMarkDelete.Name = "UIBnBookMarkDelete";
	            UIBnBookMarkDelete.TextColor = mScene.ButtonTextColor;
	            UIBnBookMarkDelete.TextFont = mScene.ButtonTextFont;
	            UIBnBookMarkDelete.Style = ButtonStyle.Custom;
	            UIBnBookMarkDelete.CustomImage = mScene.ButtonImage;
				UIBnBookMarkDelete.Visible = true;
				this.mRoot.AddChildLast(UIBnBookMarkDelete);
				
				
				UISpBookMarkListParent = new ScrollPanel();
				UISpBookMarkListParent.Name = "UISpBookMarkListParent";
				UISpBookMarkListParent.PanelColor = new UIColor(0,0,0,0);
				UISpBookMarkListParent.ScrollBarVisibility = ScrollBarVisibility.Invisible;
				UISpBookMarkListParent.VerticalScroll = true;
				UISpBookMarkListParent.HorizontalScroll = false;
				UISpBookMarkListParent.Visible = true;
				this.mRoot.AddChildLast(UISpBookMarkListParent);
				
		            UILpBookMarks = new ListPanel();
		            UILpBookMarks.Name = "UILpBookMarks";
		            UILpBookMarks.ScrollBarVisibility = ScrollBarVisibility.Invisible;
					UILpBookMarks.Visible = true;
					this.UISpBookMarkListParent.AddChildLast(UILpBookMarks);
					
					UILbBookMarkInfo = new Label();
					UILbBookMarkInfo.Name = "UILbBookMarkInfo";
					UILbBookMarkInfo.TextColor = new UIColor(0f / 255f, 0f / 255f, 0f / 255f, 255f / 255f);
					UILbBookMarkInfo.BackgroundColor = new UIColor(250f / 255f, 255f / 255f, 250f / 255f, 0f / 255f);
					UILbBookMarkInfo.HorizontalAlignment = HorizontalAlignment.Left;
					UILbBookMarkInfo.VerticalAlignment = VerticalAlignment.Top;
					UILbBookMarkInfo.Visible = true;
					this.UISpBookMarkListParent.AddChildLast(UILbBookMarkInfo);
			}
			//this.RootWidget.AddChildLast(mRoot);
			#endregion
			
			
			#region init
			DragGestureDetector drag = new DragGestureDetector();
			drag.DragDetected += HandleBookMarkListDrag;
			drag.MaxDistance = 10;
			UISpBookMarkListParent.AddGestureDetector(drag);
			
			mRoot.KeyEventReceived += HandleBookMarkListKey;
			UIBnBookMarkCurrent.ButtonAction += HandleBookMarkCurrent;
			UIBnBookMarkDelete.ButtonAction += HandleBookMarkDelete;
			
			UIBnBookMarkCurrent.Focusable = false;
			UIBnBookMarkDelete.Focusable = false;
			
			UILpBookMarks.FocusStyle = FocusStyle.None;
			UILpBookMarks.Focusable = false;
			
			UISpBookMarkListParent.FocusStyle = FocusStyle.None;
			UISpBookMarkListParent.Focusable = false;
			
			UILbBookMarkInfo.Font = mScene.FontSet.Middle;
			
			//FillBookMarks();
			//mCurrentBookMarkItem = 0;
			
			#endregion
		}
		
		public override void OnShown()
		{
			RefreshBookMarks();
		}
		
		public override void OnHidden()
		{
			if( mBookMarkButton != null )
			{
				mBookMarkButton.Clear();
				mBookMarkButton = null;
			}
			
			if( UILpBookMarks.Sections != null )
			{
				UILpBookMarks.Sections.Clear();
				UILpBookMarks.Sections = null;
			}
		}
		
		public override void UpdateLayout(LayoutOrientation orientation)
		{
			switch (orientation)
            {
            case LayoutOrientation.Vertical:
				break;
			default:
				float btnPadding = mScene.View.ButtonPadding;
				float btnWidth = mScene.View.ButtonWidth;
				float btnHeight = mScene.View.ButtonHeight;
				float Gap = 45.0f;
				//bookmarks
				mRoot.SetPosition(0,0);
				mRoot.SetSize(mScene.View.Width,mScene.View.Height);
				mRoot.Anchors = Anchors.Top | Anchors.Height | Anchors.Left | Anchors.Width;
				//mRoot.Visible = false;
				{
					float borderPadding = 6.0f;
					float titleHeight = UILbBookMarkTitle.Font.GetFont().Metrics.Height;
					UILbBookMarkTitle.SetPosition(borderPadding,borderPadding);
					UILbBookMarkTitle.SetSize(mScene.View.Width/2-borderPadding-Gap, titleHeight );
					
					UILbBookMarkListCounter.SetPosition(borderPadding,borderPadding);
					UILbBookMarkListCounter.SetSize(mScene.View.Width/2-borderPadding-Gap, titleHeight );

					UIBnBookMarkCurrent.SetPosition( mScene.View.Width-btnWidth-btnPadding, mScene.View.Height-btnHeight-btnPadding );
					UIBnBookMarkCurrent.SetSize(btnWidth, btnHeight);
					
					UIBnBookMarkDelete.SetPosition( mScene.View.Width-btnWidth*2-btnPadding*2, mScene.View.Height-btnHeight-btnPadding );
					UIBnBookMarkDelete.SetSize(btnWidth, btnHeight);
					
					UIImgBookMarkListBk.SetPosition(0,0);
					UIImgBookMarkListBk.SetSize(mScene.View.Width,UIBnBookMarkCurrent.Y - btnPadding);
					UIImgBookMarkListBk.Anchors = Anchors.Top | Anchors.Height | Anchors.Left | Anchors.Width;

					
					float height = UIBnBookMarkCurrent.Y - btnPadding - titleHeight - borderPadding*2;
					UISpBookMarkListParent.SetPosition(borderPadding,titleHeight+borderPadding);
					UISpBookMarkListParent.SetSize(mScene.View.Width-borderPadding*2,height);
					UISpBookMarkListParent.PanelWidth = UISpBookMarkListParent.Width;
					UISpBookMarkListParent.PanelHeight = height;
					
						UILpBookMarks.SetPosition(0, 0);
		                UILpBookMarks.SetSize(UISpBookMarkListParent.Width/2-Gap, height);
		                UILpBookMarks.Anchors = Anchors.Top | Anchors.Height | Anchors.Left | Anchors.Width;
					
						UILbBookMarkInfo.SetPosition(UISpBookMarkListParent.Width/2+Gap, 0);
		                UILbBookMarkInfo.SetSize(UISpBookMarkListParent.Width/2-Gap, height);
		                UILbBookMarkInfo.Anchors = Anchors.Top | Anchors.Height | Anchors.Left | Anchors.Width;
				}
				break;
			}
			
		}
		
		public override void UpdateLanguage(StreamReader reader)
		{
			String s = reader.ReadLine();
			String[] items = s.Split(',');
			int count = 0;
			if( count < items.Length )
				UILbBookMarkTitle.Text = items[count++];
			if( count < items.Length )
				UIBnBookMarkCurrent.Text = items[count++];
			if( count < items.Length )
				UIBnBookMarkDelete.Text = items[count++];
		}

		#endregion
		
		private void HandleBookMarkListKey(object sender, KeyEventArgs e)
		{
			if( this.Showing || this.Hiding )
				return;

			
			if( e.KeyEventType != KeyEventType.Up )
				return;
			
			switch(e.KeyType)
			{
			case KeyType.Triangle:	//triangle bind to refresh
				AddMarkCurrentPos();
				break;
			case KeyType.Square:
				DeleteCurrentBookMark();
				break;
			case KeyType.Up:
			case KeyType.Left:
				if( mBookMarkButton == null || mBookMarkButton.Count == 0 )
					mCurrentBookMarkItem = 0;
				else if( --mCurrentBookMarkItem < 0 )
					mCurrentBookMarkItem = mBookMarkButton.Count-1;
				UpdateSelectedBookMarkItem();
				break;
				
			case KeyType.Down:
			case KeyType.Right:
				if( mBookMarkButton == null || mBookMarkButton.Count == 0 )
					mCurrentBookMarkItem = 0;
				else if( ++mCurrentBookMarkItem >= mBookMarkButton.Count )
					mCurrentBookMarkItem = 0;
				UpdateSelectedBookMarkItem();
				break;
			case KeyType.R:
				//R/L swtich between reading/bookmarks/mainmenu
				mScene.Handler.ReadingContinue(UISwitch.LEFT);
				break;
			case KeyType.Enter:
				GotoBookMark(mCurrentBookMarkItem);
				break;
			}//switch
		}
		
		private void HandleBookMarkListDrag(object sender, DragEventArgs e)
		{
			if( this.Showing || this.Hiding )
				return;

			DragType drag = mScene.Control.DetectDrag(e.Distance.X,e.Distance.Y);
			//horizontal drag, same as keypad L
			if( drag == DragType.RIGHT )
				mScene.Handler.ReadingContinue(UISwitch.LEFT);
		}
		
		private void HandleBookMarkItem(object sender, TouchEventArgs e)
		{
			Button button = sender as Button;
			String[] s = button.Text.Split('.');
			if( s.Length < 2 )
				return;
			int index = Convert.ToInt32(s[1]);
			if( mCurrentBookMarkItem != index )
				ActivateBookMark(index);
			else
				GotoBookMark(index);
		}
		
		private void HandleBookMarkCurrent(object sender, TouchEventArgs e)
		{
			AddMarkCurrentPos();
		}

		private void HandleBookMarkDelete(object sender, TouchEventArgs e)
		{
			DeleteCurrentBookMark();
		}
		
		private void ActivateBookMark(int bookmarkIndex)
		{
			if( mScene.CurrentBook.BookMarks == null || bookmarkIndex >= mScene.CurrentBook.BookMarks.Count)
				return;
			mCurrentBookMarkItem = bookmarkIndex;
			UpdateSelectedBookMarkItem();
		}
		
		private void GotoBookMark(int bookmarkIndex)
		{
			if( mScene.CurrentBook.BookMarks == null || bookmarkIndex >= mScene.CurrentBook.BookMarks.Count)
				return;
			mCurrentBookMarkItem = bookmarkIndex;
			int pos = mScene.CurrentBook.BookMarks[bookmarkIndex];
			mScene.Handler.ReadingBookPos(pos);
		}
		
		private void AddMarkCurrentPos()
		{
			if( !mScene.IsReadingHelp() )	//don't bookmark on help
			{
				int linePOS = 0;
				if( mScene.Handler.ReadingTellPos(ref linePOS) )
				{
					BookInfo book = mScene.CurrentBook;
					
					if( book.BookMarks == null )
					{
						book.BookMarks = new List<int>();
					}
					//int index = mScene.CurrentBook.BookMarks.BinarySearch(lineNO);
					if( book.BookMarks.BinarySearch(linePOS) < 0 )
					{
						book.BookMarks.Add( linePOS );
						book.BookMarks.Sort();
						mScene.CurrentBook = book;
					}
					else
						return;
				}
			}
			RefreshBookMarks();
		}
		
		private void DeleteCurrentBookMark()
		{
			if( mBookMarkCount <= 0
			   || mScene.CurrentBook.BookMarks == null
			   || mCurrentBookMarkItem >= mScene.CurrentBook.BookMarks.Count
			   || mCurrentBookMarkItem < 0)
				return;
			
			//confirm
			String info = String.Format( mScene.Language.MsgDeleteBookMarkConfirm,mCurrentBookMarkItem);
			mScene.ConfirmMessageBox(info, ConfirmDeleteBookMark, null);
		}
		
		private void ConfirmDeleteBookMark(object dummy)
		{
			BookInfo book = mScene.CurrentBook;
			book.BookMarks.RemoveAt(mCurrentBookMarkItem);
			if( book.BookMarks.Count == 0 )
				mCurrentBookMarkItem = 0;
			else if( mCurrentBookMarkItem >= book.BookMarks.Count )
				mCurrentBookMarkItem = book.BookMarks.Count-1;
			
			mScene.CurrentBook = book;
			RefreshBookMarks();
		}
		
		private void RefreshBookMarks()
		{			
			UISpBookMarkListParent.RemoveChild( UILpBookMarks );
			float width = UILpBookMarks.Width;
			float x = UILpBookMarks.X;
			float y = UILpBookMarks.Y;
			UILpBookMarks.Dispose();
			UILpBookMarks = new ListPanel();
			UILpBookMarks.Visible = true;
			UISpBookMarkListParent.AddChildLast(UILpBookMarks);
			UILpBookMarks.SetPosition(x,y);
			UILpBookMarks.SetSize(width,UISpBookMarkListParent.PanelHeight);
			UILpBookMarks.FocusStyle = FocusStyle.None;
			UILpBookMarks.Focusable = false;
			UILpBookMarks.Anchors = Anchors.Top | Anchors.Height | Anchors.Left | Anchors.Width;
			
			FillBookMarks();
			UpdateSelectedBookMarkItem();
		}
		
		private void FillBookMarks()
		{
			this.UpdateLayout(mScene.Layout);
			
			mBookMarkButton = new List<Button>();
			mBookMarkCount = 0;
			
			int BookMarkCount;
			if( mScene.CurrentBook.BookMarks == null )
				BookMarkCount = 0;
			else
				BookMarkCount = mScene.CurrentBook.BookMarks.Count;
			
			if( LIST_BUTTON_HEIGHT*BookMarkCount >= UISpBookMarkListParent.Height )
				UISpBookMarkListParent.PanelHeight = LIST_BUTTON_HEIGHT*BookMarkCount;
			UISpBookMarkListParent.PanelX = 0;
			UISpBookMarkListParent.PanelY = 0;

			UILpBookMarks.SetListItemCreator(BookMarkItemCreator);
			ListSectionCollection section = new ListSectionCollection();
			

			section.Add( new ListSection("BookMark List", BookMarkCount) );
			UILpBookMarks.Sections = section;//.Add( new ListSection("Book List", BookCount) );

			UILpBookMarks.ShowSection = false;	
			UILpBookMarks.ShowItemBorder = false;
		}
		
		private ListPanelItem BookMarkItemCreator()
		{
			//force set height, or it will be cliped
			UILpBookMarks.Height = UISpBookMarkListParent.PanelHeight;
						
			ListPanelItem item = new ListPanelItem();
			item.SetSize(UILpBookMarks.Width, LIST_BUTTON_HEIGHT);
			item.Visible = true;
			item.BackgroundColor = mScene.ListItemColor;
			item.Focusable = false;
			
			//float Gap = 40.0f;
			float ButtonWidth = UILpBookMarks.Width;
			Button button = new Button();
			button.Name = "BookMarkItem_" + mBookMarkCount;
			button.Text = "BookMark No." + Convert.ToString( mBookMarkCount );
			button.SetPosition(0, 0);
            button.SetSize(ButtonWidth, LIST_BUTTON_HEIGHT);
            button.Anchors = Anchors.Top | Anchors.Bottom | Anchors.Left | Anchors.Right;
            button.Visible = true;
			
			button.Style = ButtonStyle.Custom;
			//button.HorizontalAlignment = HorizontalAlignment.Left;
            button.TextColor = mScene.ListItemTextColor;
            button.TextFont = mScene.ListItemTextFont;
			button.CustomImage = null;//mScene.ListImage;
			button.ButtonAction += HandleBookMarkItem;
			button.Focusable = false;
			item.AddChildLast(button);
			
			mBookMarkCount++;
			mBookMarkButton.Add ( button );
			UpdateSelectedBookMarkItem();
			return item;
		}
		
		private void UpdateSelectedBookMarkItem()
		{
			if( mScene.CurrentBook.BookMarks == null
			   || mCurrentBookMarkItem >= mScene.CurrentBook.BookMarks.Count
			   || mCurrentBookMarkItem < 0 )
			{
				UILbBookMarkInfo.Text = "";
				UILbBookMarkListCounter.Text = "0/0";
				return;
			}
			
			UILbBookMarkListCounter.Text = Convert.ToString(mCurrentBookMarkItem+1)+'/'+Convert.ToString(mBookMarkCount);
			
			for(int i = 0; i < mBookMarkButton.Count; ++i)
			{
				ListPanelItem item = mBookMarkButton[i].Parent as ListPanelItem;
				if( i == mCurrentBookMarkItem )
				{
					//mBookMarkButton[i].CustomImage = mScene.HilightListImage;
					item.BackgroundColor = mScene.ListItemHilightColor;
					EnsureListItemVisible(item, UISpBookMarkListParent);
					
					//add additional info
					const int bookmark_char_count = 256;
					mScene.Data.GetBookText(mScene.CurrentBook.BookMarks[i],bookmark_char_count, ref UILbBookMarkInfo);
				}
				else
				{
					//mBookMarkButton[i].CustomImage = mScene.ListImage;
					item.BackgroundColor = mScene.ListItemColor;
				}
			}
		}
		
	}//class
}